package com.rchat.pocmini.listener;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.service.PocService;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * @Description ：电话状态监听
 * @Author itsdf07
 * @Time 2018/1/12
 */

public class LocalPhoneStateListener extends PhoneStateListener {
    private static final String TAG = "LocalPhoneStateListener";
    private Context mContext;
    /**
     * 电话管理器
     */
    private TelephonyManager mTelephonyManager;

    /**
     * 当电话的呼叫状态发生变化的时候调用的方法
     *
     * @param state
     * @param incomingNumber
     */
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
        ALog.dTag(TAG, "state = %s", state);
        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE://空闲状态:来电挂断（本机挂断、）
                AirtalkeeAccount.getInstance().CallStop();
                PocService.isPhoneCalling = false;
                break;
            case TelephonyManager.CALL_STATE_RINGING://零响状态:来电响铃
            case TelephonyManager.CALL_STATE_OFFHOOK://通话状态:来电接听(本机主动拨打电话、)
                AirtalkeeAccount.getInstance().CallStart();
                PocService.isPhoneCalling = true;
            default:
                break;
        }
    }

    /**
     * 设置电话监听
     *
     * @param context
     * @param listenState PhoneStateListener.LISTEN_CALL_STATE
     *                    PhoneStateListener.LISTEN_NONE
     */
    public void setListener(Context context, int listenState) {
        mContext = context;
        if (mContext == null) {
            ALog.e(TAG, "电话监听设置失败，Context = null");
            return;
        }
        mTelephonyManager = (TelephonyManager) mContext.getSystemService(TELEPHONY_SERVICE);
        mTelephonyManager.listen(this, listenState);
        if (PhoneStateListener.LISTEN_NONE == listenState) {
            //取消电话监听时，释放该监听，释放上下文引用
            mContext = null;
        }
    }
}
